﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MultiDAQ_Analysis.Calculation.Calculators;
using MultiDAQ_Analysis.Calculation.Interfaces;
using MultiDAQ_Analysis.Calculation.Parameters;
using MultiDAQ_Analysis.Calculation.Results;
using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;

namespace MultiDAQ_Analysis.Calculation.Calculators
{
    public class WaterSampleCalculator : BaseMeasurementCalculator
    {
        public override string MeasurementType => "WaterSample";
        public override Type ParameterType => typeof(WaterSampleParameters);

        protected override async Task ProcessSingleRound(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            // 水样品测量单轮处理
            foreach (var kvp in context.RawData)
            {
                int channelIndex = kvp.Key;
                var (alpha, beta) = kvp.Value;

                result.ChannelResults[channelIndex] = new ChannelCalculationResult
                {
                    ChannelIndex = channelIndex,
                    AlphaResult = alpha,
                    BetaResult = beta,
                    //IsValid = alpha >= 0 && beta >= 0
                };
            }

            await Task.CompletedTask;
        }

        protected override async Task ProcessFinalCalculation(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            var parameters = context.Parameters as WaterSampleParameters;
            if (parameters == null) throw new ArgumentException("水样品测量参数类型错误");

            foreach (var channelHistory in context.HistoryData)
            {
                int channelIndex = channelHistory.Key;
                var measurements = channelHistory.Value;

                if (measurements.Count > 0)
                {
                    double alphaAvg = measurements.Average(m => m.alpha);
                    double betaAvg = measurements.Average(m => m.beta);
                    var (alphaBg, betaBg) = GetBackgroundData(channelIndex);

                    // 根据PDF公式计算水样品活度浓度
                    // C(α) = [Rs(α) - Rb(α)] × m / [es(α) × ms × V]
                    double netAlphaRate = alphaAvg - alphaBg;
                    double netBetaRate = betaAvg - betaBg;

                    var (alphaEff, betaEff) = GetEfficiencyData(channelIndex, parameters.UseStandardEfficiency);

                    double alphaConcentration = (netAlphaRate * parameters.TotalResidueAmount) /
                                              (alphaEff * parameters.TestedSampleMass * parameters.WaterVolume);
                    double betaConcentration = (netBetaRate * parameters.TotalResidueAmount) /
                                             (betaEff * parameters.TestedSampleMass * parameters.WaterVolume);

                    result.ChannelResults[channelIndex] = new ChannelCalculationResult
                    {
                        ChannelIndex = channelIndex,
                        AlphaResult = alphaConcentration, // Bq/L
                        BetaResult = betaConcentration,   // Bq/L
                        //IsValid = netAlphaRate > 0 && netBetaRate > 0 && alphaEff > 0 && betaEff > 0,
                        ExtendedResults = new Dictionary<string, double>
                        {
                            ["WaterVolume"] = parameters.WaterVolume,
                            ["TotalResidue"] = parameters.TotalResidueAmount,
                            ["TestedMass"] = parameters.TestedSampleMass,
                            ["AlphaEfficiency"] = alphaEff,
                            ["BetaEfficiency"] = betaEff,
                            ["NetAlphaRate"] = netAlphaRate,
                            ["NetBetaRate"] = netBetaRate
                        }
                    };
                }
            }

            await Task.CompletedTask;
        }

        protected override async Task SaveChannelResult(int channelIndex, ChannelCalculationResult channelResult, MeasurementCalculationResult overallResult)
        {
            var channelData = ChannelDataManager.LoadChannelData(channelIndex);

            if (channelData.MeasurementResults == null)
                channelData.MeasurementResults = new MeasurementResultData();

            channelData.MeasurementResults.WaterSampleResult = new WaterSampleMeasurementResult
            {
                AlphaConcentration = channelResult.AlphaResult,
                BetaConcentration = channelResult.BetaResult,
                MeasurementTime = DateTime.Now,
                SampleVolume = channelResult.ExtendedResults.GetValueOrDefault("WaterVolume", 0)
            };

            ChannelDataManager.SaveChannelData(channelIndex, channelData);
            await Task.CompletedTask;
        }

        private (double alphaEff, double betaEff) GetEfficiencyData(int channelIndex, bool useStandardEfficiency)
        {
            try
            {
                var channelData = ChannelDataManager.LoadChannelData(channelIndex);
                if (useStandardEfficiency)
                {
                    return (channelData.WorkConditions.AlphaStandardEfficiency,
                           channelData.WorkConditions.BetaStandardEfficiency);
                }
                else
                {
                    return (channelData.WorkConditions.AlphaWorkEfficiency,
                           channelData.WorkConditions.BetaWorkEfficiency);
                }
            }
            catch
            {
                return (0.00035, 0.003); // 默认效率值
            }
        }
    }
}